package edu.sysu.cshare.control;

import java.sql.Connection;
import java.util.List;

import org.hibernate.Session;

import edu.sysu.cshare.dao.Course;
import edu.sysu.cshare.dao.User;
import edu.sysu.cshare.util.ContinueFTP;
import edu.sysu.cshare.util.HibernateSessionFactory;
import edu.sysu.cshare.util.MD5;

public class PersonalInfoManager {
	public PersonalInfoManager(User actor) {
		this.actor = actor;
	}

	private User actor;

	// TODO 一个账号同时登陆
	/**
	 * @param id
	 *            用户id
	 * @param password
	 *            未经过MD5加密的 用户密码
	 * @return 验证成功 User 对象
	 * @throws Exception
	 * 
	 */
	public static User login(String id, String password) throws Exception {
		//NOTE may should check if ftp is on
		
		Session ss = HibernateSessionFactory.getSession();
		User u = null;
		ss.beginTransaction();
		u = (User) (ss.createQuery(" from User u where u.id = :id").setString(
				"id", id).uniqueResult());
		if (u == null) {
			throw new Exception("user not exist!");
		}
		if (MD5.getMD5(password).equals(u.getPassword())) {
			u.setLastIP(u.getLastIP());
			ss.save(u);
			ss.getTransaction().commit();
		} else {
			throw new Exception("validate failure!");
		}
		return u;

	}

	/**
	 * 
	 * @param newpassword
	 *            新的明文密码
	 */

	// TODO 修改密码下次登陆生效?
	public void changePassword(String newpassword) {
		Session ss = HibernateSessionFactory.getSession();
		ss.beginTransaction();
		/*
		ss.createQuery(
				"update User u set u.password = :newpwd where u.id = :uid ")
				.setString("newpwd", MD5.getMD5(newpassword))
				.setString("uid", actor.getId()).executeUpdate();*/
		actor.setPassword(MD5.getMD5(newpassword));
		ss.save(actor);
		ss.getTransaction().commit();
	}

	public void selectCourse(Course course) {
		Session ss = HibernateSessionFactory.getSession();
		actor.addCourse(course);
		ss.beginTransaction();
		// NOTE 貌似在一方存就可以
		// ss.save(course);
		ss.save(actor);
		ss.getTransaction().commit();

	}

	public void selectCourses(List<Course> courses) {
		Session ss = HibernateSessionFactory.getSession();
		actor.addCourses(courses);
		ss.beginTransaction();
		ss.save(actor);
		ss.getTransaction().commit();
	}

	public void quitCourse(Course course) {
		Session ss = HibernateSessionFactory.getSession();
		actor.delCourse(course);

		ss.beginTransaction();
		// NOTE 貌似在一方存就可以
		// ss.save(course);
		ss.save(actor);
		ss.getTransaction().commit();
	}

	public void quitCourses(List<Course> courses) {
		Session ss = HibernateSessionFactory.getSession();

		actor.delCourses(courses);
		ss.beginTransaction();
		ss.save(actor);
		ss.getTransaction().commit();
	}
}
